package io.renren.modules.tbposition.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@ServerEndpoint("/websocket/pos")
@Slf4j
public class PosWebSocketService {

    //定义session
    private Session session;

    //定义一个存储session的容器

    private static CopyOnWriteArraySet<PosWebSocketService> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void OnOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        log.info("有新连接，总数：" + webSocketSet.size());
    }

    @OnClose
    public void OnClose(){
        webSocketSet.remove(this);
        log.info("连接断开，总数：" + webSocketSet.size());
    }

    @OnMessage
    public void OnMessage(String message,Session session){
        log.info("收到客户端"+session.getId()+"发来的消息：" + message);
        sendMessage("收到消息：" + message);
    }

    public synchronized void sendMessage(String message){
        for(PosWebSocketService posWebSocketService: webSocketSet){
            log.info("广播消息,message={}",message);
            try {
                    posWebSocketService.session.getBasicRemote().sendText(message);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
